<?php

class newsLetterkTask extends sfBaseTask
{
	protected function configure()
	{
		// // add your own arguments here
		// $this->addArguments(array(
		//   new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'),
		// ));

		$this->addOptions(array(
		new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'backend'),
		new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
		new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
		new sfCommandOption('id_mailing', null, sfCommandOption::PARAMETER_OPTIONAL, 'ID Mailing', '')
		));

		$this->namespace        = 'newsletter';
		$this->name             = 'task';
		$this->briefDescription = '';
		$this->detailedDescription = <<<EOF
The [namespace:task|INFO] task does things.
Call it with:

  [php symfony newletter:task|INFO]
EOF;
	}

	protected function execute($arguments = array(), $options = array())
	{
		// initialize the database connection
		$databaseManager = new sfDatabaseManager($this->configuration);
		$connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
		
		$id_mailing = null;
		if(isset($options['id_mailing']))
			$id_mailing = $options['id_mailing'];
		
		$dir_arquivo = sfConfig::get('sf_upload_dir').'/newsletter/'.$id_mailing.'.txt';
		
		$mmgs = MailingTable::carregarMailingEnviar($id_mailing);
		$handle = fopen($dir_arquivo, 'a+');
		
		// pegos os grupos
		foreach($mmgs as $mmg){
			$mg = $mmg['MailingGroup'];
			$m = $mmg['Mailing'];
			
			// para cada grupo eu pegos os usuários
			fwrite($handle, 'Start: ' . date('d/m/Y H:i:s') . "\r\n");
			fwrite($handle, 'Grupo: ' . $mg->getNmMailingGroup() . "\r\n");
			
			// pego os usuários do grupo
			$mls = $mg['MailingList'];
			
			foreach($mls as $ml)
			{
				$this->enviarEmail($m, $ml, $handle);
				sleep(2);
			}
			
			fwrite($handle, 'Final: ' . date('d/m/Y H:i:s') . "\r\n");
			sleep(10);
		}

		fclose($handle);
		
		if($id_mailing != null)
		{
			$mailing = Doctrine::getTable('Mailing')->find($id_mailing);
			$mailing->set('st_mailing', 1);
			$maling->save();
		}
	}
	
	private function enviarEmail($m, $ml, $handle)
	{
		// class initialization
	    $mail = new sfMail();
	    $mail->setCharset('iso-8859-1');

	    // definition of the required parameters
	    $mail->setSender('contato@terapiavital.com.br', "TerapiaVital");
	    $mail->setFrom('contato@terapiavital.com.br', "TerapiaVital");
	    $mail->addReplyTo('contato@terapiavital.com.br');
		
	    $mail->addAddress($ml->getDsEmailList(), $ml->getDsNomeList());

	    $mail->setSubject('TerapiaVital | ' . $m->getNmMailing());
	    $mail->setContentType('text/html');
		
	    $msg = $m->getDsMailing().
	    $msg .= "<br /><br />
	            Esta é uma mensagem gerada automaticamente pelo sistema.<br />
	            Por favor, não responda. Pois, neste caso, a mesma será descartada.";

	    $mail->setBody($msg);
   	 	$mail->send();
   	 	
   	 	fwrite($handle, $ml->getDsNomeList() . ' = ' . $ml->getDsEmailList() . "\r\n");
	}
}

